package com.wxy.ej.flow.modules.act.listen;

import com.rt.easyjava.common.base.UserDetailsDto;
import com.rt.easyjava.common.utils.others.StringUtils;
import com.wxy.ej.flow.modules.act.dto.UserDto;
import com.wxy.ej.flow.modules.act.repository.JdbcActRepository;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.Expression;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 任务调用前，根据规则编号，创建业务系统部门任务和人员，同时返回部门和人员信息。
 * 子流程调用了4次（4个机构）
 * 1001
 * [1001, 1002, 1003, 1004]
 */
@Slf4j
@Component("assigneeListener")
@Scope("prototype")
public class AssigneeListener implements ExecutionListener {

    private Expression assigneeSql;
    private Expression fork;
    private Expression insertDb;
    private Expression varPre;

    @Resource
    JdbcActRepository jdbcActRepository;
    @Resource
    HttpServletRequest request;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        log.info("---->act listener: AssigneeListener");
        log.info(delegateExecution.getEventName());
        log.info(delegateExecution.getCurrentFlowElement().getName());
        String assigneeSqlStr = assigneeSql==null?null:assigneeSql.getExpressionText();
        String forkStr = fork==null?null:fork.getExpressionText();
        log.info(assigneeSqlStr);
        log.info(forkStr);
        List<UserDto> userList = null;

        // 用户任务多实例时，主流程和多实例流程，都执行这个方法
        System.out.println("==========>11111111111:start "+delegateExecution.getCurrentFlowElement().getName());
        System.out.println("getId:"+delegateExecution.getId());
        System.out.println("is main:"+delegateExecution.getParentId().equals(delegateExecution.getProcessInstanceId()));
        System.out.println("getParentId:"+delegateExecution.getParentId());
        System.out.println("getRootProcessInstanceId:"+delegateExecution.getRootProcessInstanceId());
        System.out.println("getProcessInstanceId:"+delegateExecution.getProcessInstanceId());
        if (!delegateExecution.getParentId().equals(delegateExecution.getProcessInstanceId())) {
            return;
        }
        log.info("---->act listener: run");

        if (!StringUtils.isNull(assigneeSql)) {
            /*
            前端sql中的变量
            ${loginUserId}:当前登录用户ID<br/>
            ${loginName}:当前登录用户登录名<br/>
            ${loginUserDeptId}:当前登录用户部门Id<br/>
            ${loginUserDeptCode}:当前登录用户部门编号<br/>
            */
            //取登录用户
            UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(request.getParameter("userDetailsJson"));
            if (userDetailsDto!=null) {
                assigneeSqlStr = assigneeSqlStr.replace("${loginUserId}", userDetailsDto.getUserId());
                assigneeSqlStr = assigneeSqlStr.replace("${loginName}", userDetailsDto.getLoginName());
                assigneeSqlStr = assigneeSqlStr.replace("${loginUserDeptId}", userDetailsDto.getDeptId());
                assigneeSqlStr = assigneeSqlStr.replace("${loginUserDeptCode}", userDetailsDto.getDeptCode());
            }
            log.info("assigneeSqlStr:{}",assigneeSqlStr);
            userList = jdbcActRepository.executeSql(assigneeSqlStr);
            log.info("userList:{}",userList);

            if (userList==null) {
                log.error("AssigneeListener userList is null");
                return;
            }

            // [{userId:'', userName:'', answerId:'', phone:'', email:''}]
            delegateExecution.setVariable("assigneeCount", userList.size()); // 人数
            delegateExecution.setVariable("userList", userList); // 所有系统用户 userId>0
            return;
        }


        // Timer: 指定人员
        String assigneeUserId = (String) delegateExecution.getVariable("assigneeUserId");
        if (!StringUtils.isNull(assigneeUserId)) {
            userList = new ArrayList<>();
            UserDto userDto = new UserDto();
            userDto.setUserId(assigneeUserId);
            userList.add(userDto);
            delegateExecution.setVariable("assigneeCount", userList.size()); // 人数
            delegateExecution.setVariable("userList", userList); // 所有系统用户 userId>0
            // 删除变量
            delegateExecution.removeVariable("assigneeUserId");
            return;
        }


        throw new RuntimeException("缺少指派sql");
    }


}
